#!/usr/bin/env python3
"""
自动监控STM32 USB CDC设备并读取输出
"""

import serial
import time
import subprocess
import sys
import os

SUDO_PASSWORD = "123"
BAUDRATE = 115200
DEVICE_PATTERN = "/dev/ttyACM"

def run_sudo_command(cmd):
    """使用sudo执行命令"""
    full_cmd = f"echo {SUDO_PASSWORD} | sudo -S {cmd}"
    try:
        result = subprocess.run(full_cmd, shell=True, capture_output=True, text=True, timeout=5)
        return result.returncode == 0
    except Exception as e:
        print(f"执行命令失败: {e}")
        return False

def find_device():
    """查找USB CDC设备"""
    for i in range(10):
        device = f"{DEVICE_PATTERN}{i}"
        if os.path.exists(device):
            return device
    return None

def set_device_permission(device):
    """设置设备权限"""
    print(f"设置设备权限: {device}")
    return run_sudo_command(f"chmod 666 {device}")

def monitor_device(device):
    """监控设备输出"""
    print(f"\n{'='*60}")
    print(f"开始监控设备: {device}")
    print(f"{'='*60}\n")
    
    try:
        ser = serial.Serial(device, BAUDRATE, timeout=0.1)
        print("✅ 串口已打开\n")
        
        # 持续读取数据
        empty_count = 0
        while True:
            if ser.in_waiting > 0:
                data = ser.read(ser.in_waiting)
                try:
                    text = data.decode('utf-8', errors='replace')
                    print(text, end='', flush=True)
                    empty_count = 0
                except Exception as e:
                    print(f"\n[解码错误: {e}]\n")
                    empty_count = 0
            else:
                time.sleep(0.1)
                empty_count += 1
                
                # 每10秒检查一次设备是否还在
                if empty_count >= 100:
                    if not os.path.exists(device):
                        print(f"\n\n❌ 设备 {device} 已断开\n")
                        ser.close()
                        return False
                    empty_count = 0
                    
    except serial.SerialException as e:
        print(f"\n❌ 串口错误: {e}\n")
        return False
    except KeyboardInterrupt:
        print(f"\n\n⚠️  用户中断\n")
        ser.close()
        return True
    except Exception as e:
        print(f"\n❌ 错误: {e}\n")
        return False

def main():
    """主函数"""
    print("\n" + "="*60)
    print("STM32 USB CDC 自动监控脚本")
    print("="*60)
    print("功能:")
    print("  1. 自动检测USB CDC设备")
    print("  2. 自动设置设备权限")
    print("  3. 实时显示设备输出")
    print("  4. 设备断开后自动重新检测")
    print("\n按 Ctrl+C 退出")
    print("="*60 + "\n")
    
    last_device = None
    
    while True:
        # 查找设备
        device = find_device()
        
        if device:
            if device != last_device:
                print(f"🔍 发现设备: {device}")
                
                # 设置权限
                if not set_device_permission(device):
                    print(f"❌ 设置权限失败，等待1秒后重试...\n")
                    time.sleep(1)
                    continue
                
                # 等待设备稳定
                time.sleep(0.5)
                
                # 开始监控
                last_device = device
                user_quit = monitor_device(device)
                
                if user_quit:
                    print("程序退出")
                    break
                
                # 设备断开，重置last_device
                last_device = None
        else:
            if last_device is not None:
                print("⏳ 等待设备连接...\n")
                last_device = None
            time.sleep(0.5)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n程序退出\n")
        sys.exit(0)

